package cn.dnuifood_cjy.dnuifood_16110100529.controller;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.List;

import cn.dnuifood_cjy.dnuifood_16110100529.R;
import cn.dnuifood_cjy.dnuifood_16110100529.db.RecordDBOperation;
import cn.dnuifood_cjy.dnuifood_16110100529.db.RecordSQLiteOpenHelper;
import cn.dnuifood_cjy.dnuifood_16110100529.view.HistoryListView;


public class SearchFragment extends BaseFragment {
    private View view;
    private Button btn_ok;
    private TextView tv_clear,tv_tip;
    private HistoryListView listView;
    private EditText et_search;
    private RecordDBOperation recordDBOperation;
    RecordSQLiteOpenHelper helper =new RecordSQLiteOpenHelper(getContext());
    final RecordDBOperation recordDB = new RecordDBOperation(helper);
    public SearchFragment() {
        // Required empty public constructor
    }
    @Override
    public void onViewCreated(@NonNull View views, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(views, savedInstanceState);
        this.view=views;
        SharedPreferences sharedPreferences = views.getContext().getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        String user_id = sharedPreferences.getString("user_id","user_id");
        initViews();
        // initEvents();
        initEvent1();
    }

    public void initEvent1(){
        RecordSQLiteOpenHelper helper =new RecordSQLiteOpenHelper(getContext());
        final RecordDBOperation recordDB = new RecordDBOperation(helper);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  recordDB.insertData(et_search.getText().toString().trim());
                showDetailInfo(et_search.getText().toString().trim());
            }
        });

    }

    public void initEvents(){
        RecordSQLiteOpenHelper helper =new RecordSQLiteOpenHelper(getContext());
        final RecordDBOperation recordDB = new RecordDBOperation(helper);
        tv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recordDB.deleteData();
                showData("");
            }
        });

        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // recordDB.insertData(et_search.getText().toString().trim());
                showDetailInfo(et_search.getText().toString().trim());
            }
        });
        //搜索框的键盘搜索键点击回调
        et_search.setOnKeyListener(new View.OnKeyListener() {//输入完后按键盘上的搜索键
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){
                    //修改回车键功能
                    //先隐藏键盘
                    ((InputMethodManager)
                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                    //按完搜索键后将当前查询的关键字保存起来，如果关键字已经存在就不执行保存
                    boolean hasData = recordDB.hasData(et_search.getText().toString().trim());
                    if (!hasData){
                        recordDB.insertData(et_search.getText().toString().trim());
                        showData("");
                    }
                    //根据输入内容模糊查询商品，并且跳转到另一个页面
                    showDetailInfo(et_search.getText().toString().trim());
                }
                return false;
            }
        });

        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                btn_ok.setVisibility(View.VISIBLE);
                if (s.toString().trim().length() ==0){
                    tv_tip.setText("搜索历史");
                }else {
                    tv_tip.setText("搜索结果");
                }
                String tempName = et_search.getText().toString();
                showData(tempName);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView)view.findViewById(R.id.text1);
                String name = textView.getText().toString();
                et_search.setText(name);
                showDetailInfo(name);
            }
        });
    }

    public void initViews(){
        btn_ok=view.findViewById(R.id.btn_ok);
        tv_clear=view.findViewById(R.id.tv_clear);
        et_search=view.findViewById(R.id.et_search);
        listView=view.findViewById(R.id.listView);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_search, container, false);
    }

    void showData(String tempName){
        //创建adapter对象
        List list =recordDB.queryData(tempName);
        SimpleAdapter adapter = new SimpleAdapter(getActivity(),list,R.layout.simple_list_items,new String[]{"name"},new int[]{R.id.text1});

        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    void showDetailInfo(String name){
        //跳转到搜索结果界面

        //intent.putExtra("shop_id",entity.getShop_id());
        if (!name.equals(" ")) {
            Intent intent = new Intent(getActivity(), SearchResultActivity.class);
            intent.putExtra("search", name);
            startActivity(intent);
        }
    }

}
